package com.example.blogcommon.utils;

import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import java.io.UnsupportedEncodingException;
import java.util.Optional;

public class Mail {

    private JavaMailSender javaMailSender;

    private MailProperties mailProperties;

    public Mail(JavaMailSender javaMailSender, MailProperties mailProperties) {
        this.javaMailSender = javaMailSender;
        this.mailProperties = mailProperties;
    }



    public void send(String to,String subject,String content) throws MessagingException, UnsupportedEncodingException {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();

        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage,false);

        String personal = Optional.ofNullable(mailProperties.getProperties().get("personal")).orElse(mailProperties.getUsername());
        //发件人邮箱和名称
        mimeMessageHelper.setFrom(mailProperties.getUsername(),personal);
        //收件人
        mimeMessageHelper.setTo(to);
        //标题
        mimeMessageHelper.setSubject(subject);
        //内容
        mimeMessageHelper.setText(content,true);

        javaMailSender.send(mimeMessage);
    }
}
